﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using FinPlusCommon;
using u = FinPlusUtility.Utility;
using log = Logger.Logger;

namespace FinPlusWPFControls
{
    //Note Prime use edit template columns use primative controls for data template
    public partial class FinPlusValueQuoteHit : FinPlusControl
    {
        public override string Id { get { return GetValue(IdProperty).ToString(); } set { } }
        public override string[] TestStates { get { return new string[] { "TestString", "ViewString", "IsValid" }; } }
        public override string TestString { get { return string.Format("{0}|{1}", IsEnabled, Quote); } }
        public override string ContainerId { get { return GetValue(LinkedIdProperty).ToString(); } }

        public string ViewString { get { return string.Format("{0}|{1}", textBlock.IsEnabled, textBlock.Text); } }
        public string FunctionName { get { return GetValue(FunctionNameProperty).ToString(); } set { } }
        public string Quote { get { return GetValue(QuoteProperty).ToString(); } set { SetValue(QuoteProperty, value); } }
        public string Publish { get { return GetValue(PublishProperty).ToString(); } set { SetValue(PublishProperty, value); } }
        public new bool IsEnabled { get { return (bool)GetValue(IsEnabledProperty); } set { } }
        public int Status { get { return (int)GetValue(StatusProperty); } set { SetValue(StatusProperty, value); } }
        public string StringFormat { get { return GetValue(StringFormatProperty).ToString(); } }


        public static readonly DependencyProperty IdProperty = DependencyProperty.Register(Propertys.Id.ToString(), typeof(string), typeof(FinPlusValueQuoteHit));
        public static readonly DependencyProperty FunctionNameProperty = DependencyProperty.Register(Propertys.FunctionName.ToString(), typeof(string), typeof(FinPlusValueQuoteHit));
        public static readonly DependencyProperty QuoteProperty = DependencyProperty.Register(Propertys.Price.ToString(), typeof(string), typeof(FinPlusValueQuoteHit), new UIPropertyMetadata(Callback));
        public static readonly DependencyProperty PublishProperty = DependencyProperty.Register(Propertys.Publish.ToString(), typeof(string), typeof(FinPlusValueQuoteHit));
        public new static readonly DependencyProperty IsEnabledProperty = DependencyProperty.Register(Propertys.ReadOnly.ToString(), typeof(bool), typeof(FinPlusValueQuoteHit));
        public static readonly DependencyProperty StatusProperty = DependencyProperty.Register(Propertys.Status.ToString(), typeof(int), typeof(FinPlusValueQuoteHit));
        public static readonly DependencyProperty StringFormatProperty = DependencyProperty.Register(Propertys.StringFormat.ToString(), typeof(string), typeof(FinPlusValueQuoteHit));
        public static readonly DependencyProperty LinkedIdProperty = DependencyProperty.Register(Propertys.LinkedId.ToString(), typeof(string), typeof(FinPlusValueQuoteHit));

        private enum Propertys { Id, FunctionName, Instrument, Price, BuySell, Size, Source, QuoteStyle, Publish, ReadOnly, Status, StringFormat, LinkedId }
        private enum Params { Id, Quote, QuoteInstrument }
        private IFunction _quote;
        private Permission _perm;
        private double _prev = double.MinValue;
        private bool _hasSetEnable;

        //construct
        public FinPlusValueQuoteHit()
        {
            InitializeComponent();
            IsValid = true;

            textBlock.Cursor = ((TextBlock)this.Resources["CHit"]).Cursor;
        }

        //common control interface
        public override void CmdExecute(IFunction command) 
        {
            try
            {
                CmdCapture(command);

                switch ((Cmds)Enum.Parse(typeof(Cmds), command.Name, true))
                {
                    case Cmds.OpenQuote: OpenQuote(); break;
                    default: throw new Exception(string.Format("event not recognised {0}", command.Name));
                }
            }
            catch (CmdExecuteException e)
            {
                log.Log(Logger.Level.Error, Id, Config, e.Message, e);
            }
        }

        //public
        public void Callback(string reply)
        {
            Publish = reply;
        }

        //private
        private void OpenQuote()
        {
            if (!_hasSetEnable || _quote == null) return;
            
            var quote = new Function(_quote.ToArray());
            
            if (_perm == null)  _perm = GetPermission(Params.QuoteInstrument.ToString(), Params.Id.ToString(), _quote.Get(Params.Id.ToString()).Value);

            if (!_perm.CanWrite) return;

            FinPlusValueQuotePopup.Show(quote, Id, Callback, ContainerId);

            //((MediaPlayer)this.FindResource("SoundBlop")).Play();
            System.Media.SystemSounds.Beep.Play();
        }
        
        private void SetControl(DependencyPropertyChangedEventArgs a)
        {
            //permission
            if (!_hasSetEnable)
            {
                _hasSetEnable = true;
            }

            if (string.IsNullOrEmpty(a.NewValue.ToString()))
            {
                textBlock.Text = "-";
                return;
            }

            _quote = new Function((object[,])u.StringToArray2d(a.NewValue.ToString()));
            double newValue;
            if (double.TryParse(_quote[Params.Quote.ToString()].ToString(), out newValue))
            {
                textBlock.Text = newValue.ToString();
                textBlock.Foreground = newValue < 0 ? Brushes.Red : Brushes.Black;
                Status = _prev == double.MinValue ? 0 : newValue > _prev ? 1 : -1;
                _prev = newValue;
            }
            else
            {
                textBlock.Text = "-";
            }
        }

        //cmds
        private enum Cmds { OpenQuote }

        //event
        private static void Callback(DependencyObject d, DependencyPropertyChangedEventArgs a) { ((FinPlusValueQuoteHit)d).SetControl(a); }
        private void HitQuote(object s, MouseButtonEventArgs a)
        {
            if (a.LeftButton == MouseButtonState.Pressed && a.ClickCount == 2)
                CmdRouter(Cmds.OpenQuote.ToString());
       }
    }   
}
